import {useEffect, useState} from 'react';
import { Select } from 'antd';
import { listAll } from '@/services/system/role';

const { Option } = Select;

const SystemRoleSelect = (props) => {
  const {onChange, value, placeholder, multiple} = props;

  const [listDate, handleListDate] = useState([]);
  const [roleValue, handleRoleValue] = useState(undefined);

  useEffect( () => {
    const lostData = async () => {
      const result = await listAll();
      handleListDate(result.data)
    };

    lostData().then(() =>{
      handleRoleValue(value || undefined)
    });
  }, []);

  const selectItem = (e) => {
    handleRoleValue(e)
    onChange(e)
  }

  const options = listDate.map(role => <Option key={role.id} value={role.id}> {role.name} </Option>);

  return (
    multiple ? (
      <Select onChange={selectItem} mode='multiple' value={roleValue} placeholder={placeholder}>
        {options}
      </Select>
    ) : (
      <Select onChange={selectItem} value={roleValue} placeholder={placeholder}>
        {options}
      </Select>
    )
  )
}

export default SystemRoleSelect;